import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base/generated/l10n.dart';
import 'package:flutter_base/src/common/widgets/confirm_alter_dialog.dart';
import 'package:flutter_base/src/common/widgets/custom_bottom_picker.dart';
import 'package:flutter_base/src/common/widgets/custom_date_picker.dart' as custom_picker;
import 'package:flutter_base/src/common/widgets/custom_linked_picker.dart';
import 'package:flutter_base/src/common/widgets/custom_triple_linked_picker.dart';
import 'package:flutter_base/src/common/widgets/image_viewer.dart';
import 'package:flutter_base/src/config/app_colors.dart';
import 'package:flutter_base/src/network/http.dart';
import 'package:flutter_base/src/provider/locale_provider.dart';
import 'package:flutter_base/src/provider/theme_provider.dart';
import 'package:flutter_base/src/config/color_util.dart';
import 'package:flutter_base/src/utils/loading_utils.dart';
import 'package:flutter_base/src/utils/tool.dart';
import 'package:provider/provider.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  DateTime _editDateTime = DateTime.now();

  void _handleInfo() async {
    try {
      LoadingUtils.showLoading(context: context);
      var res = await httpApi.getResponse(
        '/v1/www/search/searchKey',
      );
      debugPrint('请求成功: $res');
    } catch (e) {
      debugPrint('请求错误: $e');
    } finally {
      LoadingUtils.dismissLoading();
    }
  }

  void _switchLanguage(Locale locale) {
    final localeProvider = Provider.of<LocaleProvider>(context, listen: false);
    localeProvider.setLocale(locale);
  }

  void _handleImageTap() {
    MultiImageViewer.show(context, imageUrls: ['https://picsum.photos/800/600']);
  }

  void _showBottomPicker(BuildContext context) {
    // 准备选项数据 - 使用Map列表代替字符串列表
    final List<Map<String, dynamic>> options = [
      {
        'id': 1,
        'name': '其他选择项1',
        'value': 'option1',
        'children': [
          {'id': 11, 'name': '子项11', 'value': 'option11'},
          {'id': 11, 'name': '子项12', 'value': 'option11'},
          {'id': 11, 'name': '子项13', 'value': 'option11'},
          {'id': 11, 'name': '子项14', 'value': 'option11'},
        ],
      },
      {
        'id': 2,
        'name': '其他选择项2',
        'value': 'option2',
        'children': [
          {'id': 21, 'name': '子项21', 'value': 'option21'},
          {'id': 22, 'name': '子项22', 'value': 'option22'},
          {'id': 23, 'name': '子项23', 'value': 'option23'},
          {'id': 24, 'name': '子项24', 'value': 'option24'},
        ],
      },
      {
        'id': 3,
        'name': '目前选中项3',
        'value': 'option3',
        'children': [
          {'id': 31, 'name': '子项31', 'value': 'option31'},
          {'id': 32, 'name': '子项32', 'value': 'option32'},
          {'id': 33, 'name': '子项33', 'value': 'option33'},
          {'id': 34, 'name': '子项34', 'value': 'option34'},
        ],
      },
      {
        'id': 4,
        'name': '其他选择项4',
        'value': 'option4',
        'children': [
          {'id': 41, 'name': '子项41', 'value': 'option41'},
        ],
      },
      {
        'id': 5,
        'name': '其他选择项5',
        'value': 'option5',
        'children': [
          {'id': 51, 'name': '子项51', 'value': 'option51'},
          {'id': 52, 'name': '子项52', 'value': 'option52'},
          {'id': 53, 'name': '子项53', 'value': 'option53'},
          {'id': 54, 'name': '子项54', 'value': 'option54'},
        ],
      },
    ];

    // 显示底部选择器
    CustomBottomPicker.show(
      context: context,
      title: '这里是标题',
      options: options,
      displayKey: 'name', // 指定显示'name'键的值
      initialIndex: 2, // 默认选中"目前选中项"
      onConfirm: (index, selectedItem) {
        // 返回整个选中项
        print('-------$index-------$selectedItem');
        print('已选择: ${selectedItem['name']} (ID: ${selectedItem['id']}, 值: ${selectedItem['value']})');
      },
      pickerHeight: 300,
    );
  }

  void _showLinkedPicker(BuildContext context) {
    // 您提供的数据源
    final List<Map<String, dynamic>> options = [
      {
        'id': 1,
        'name': '水果',
        'value': 'fruit',
        'children': [
          {'id': 11, 'name': '苹果', 'value': 'apple'},
          {'id': 12, 'name': '香蕉', 'value': 'banana'},
          {'id': 13, 'name': '橙子', 'value': 'orange'},
        ],
      },
      {
        'id': 2,
        'name': '蔬菜',
        'value': 'vegetable',
        'children': [
          {'id': 21, 'name': '菠菜', 'value': 'spinach'},
          {'id': 22, 'name': '胡萝卜', 'value': 'carrot'},
        ],
      },
      {
        'id': 3,
        'name': '主食',
        'value': 'staple',
        'children': [
          {'id': 31, 'name': '米饭', 'value': 'rice'},
          {'id': 32, 'name': '面条', 'value': 'noodles'},
          {'id': 33, 'name': '面包', 'value': 'bread'},
        ],
      },
      {
        'id': 4,
        'name': '饮料',
        'value': 'drink',
        // 这个选项没有子项，用于测试边界情况
        'children': [],
      },
    ];
    String _selectedResult = '';
    CustomLinkedPicker.show(
      context: context,
      title: '请选择分类',
      options: options,
      // 设置初始选中项
      initialParentIndex: 2, // 初始选中“主食”
      initialChildIndex: 1, // 初始选中“面条”
      onConfirm: (selectedParent, selectedChild) {
        setState(() {
          if (selectedChild != null) {
            _selectedResult = "${selectedParent['name']} - ${selectedChild['name']}";
          } else {
            _selectedResult = "选择了 ${selectedParent['name']}, 但它没有子项";
          }
          print(_selectedResult);
        });
        // 打印完整数据
        print('父级: $selectedParent');
        print('子级: $selectedChild');
      },
      onCancel: () {
        print("用户取消了选择");
      },
    );
  }

  void _showTripleLinkedPicker(BuildContext context) {
    // 模拟的省市区三级数据
    final List<Map<String, dynamic>> cityData = [
      {
        'name': '浙江省',
        'children': [
          {
            'name': '杭州市',
            'children': [
              {'name': '西湖区'},
              {'name': '上城区'},
              {'name': '余杭区'},
            ],
          },
          {
            'name': '宁波市',
            'children': [
              {'name': '海曙区'},
              {'name': '江北区'},
              {'name': '镇海区'},
            ],
          },
        ],
      },
      {
        'name': '江苏省',
        'children': [
          {
            'name': '南京市',
            'children': [
              {'name': '玄武区'},
              {'name': '秦淮区'},
              {'name': '建邺区'},
              {'name': '鼓楼区'},
            ],
          },
          {
            'name': '苏州市',
            'children': [
              {'name': '姑苏区'},
              {'name': '虎丘区'},
              {'name': '吴中区'},
            ],
          },
        ],
      },
      {
        'name': '北京市',
        // 第二级没有子项的情况
        'children': [
          {
            'name': '北京市',
            'children': [
              {'name': '东城区'},
              {'name': '西城区'},
              {'name': '朝阳区'},
              {'name': '海淀区'},
            ],
          },
        ],
      },
    ];

    String _selectedResult = '';
    CustomTripleLinkedPicker.show(
      context: context,
      title: '请选择地区',
      options: cityData,
      // 设置初始选中项：江苏省-苏州市-吴中区
      initialCol1Index: 1,
      initialCol2Index: 1,
      initialCol3Index: 2,
      onConfirm: (col1, col2, col3) {
        setState(() {
          final col1Name = col1['name'];
          final col2Name = col2?['name'] ?? '';
          final col3Name = col3?['name'] ?? '';
          _selectedResult = '$col1Name - $col2Name - $col3Name';
          print(_selectedResult);
        });
      },
      onCancel: () {
        print("用户取消了选择");
      },
    );
  }

  void _showDateTimePicker(BuildContext context) {
    print('object');
  }

  @override
  Widget build(BuildContext context) {
    final currentLocale = Provider.of<LocaleProvider>(context).locale;
    final isChineseSelected = currentLocale.languageCode == 'zh';

    // 获取国际化实例
    final l10n = AppL10n.of(context);

    return Scaffold(
      backgroundColor: const Color(0xFFFEFEFE),
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: Text(l10n.homePageTitle),
        actions: [
          IconButton(
            icon: const Icon(Icons.language),
            tooltip: l10n.switchLanguage,
            onPressed: () {
              showDialog(
                context: context,
                builder: (context) => AlertDialog(
                  title: Text(l10n.selectLanguage),
                  content: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      ListTile(
                        title: const Text('中文'),
                        leading: Radio<bool>(
                          value: true,
                          groupValue: isChineseSelected,
                          onChanged: (value) {
                            _switchLanguage(const Locale('zh', 'CN'));
                            Navigator.pop(context);
                          },
                        ),
                      ),
                      ListTile(
                        title: const Text('English'),
                        leading: Radio<bool>(
                          value: false,
                          groupValue: isChineseSelected,
                          onChanged: (value) {
                            _switchLanguage(const Locale('en', 'US'));
                            Navigator.pop(context);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
          // 添加一个菜单按钮，用于切换主题
          PopupMenuButton<ThemeMode>(
            onSelected: (ThemeMode mode) {
              // 当用户选择一个选项时，调用 Provider 的方法来更新主题
              // 使用 listen: false 是因为我们在这里只是触发一个动作，不需要重建这个按钮
              Provider.of<ThemeProvider>(context, listen: false).setThemeMode(mode);
            },
            itemBuilder: (BuildContext context) => <PopupMenuEntry<ThemeMode>>[
              const PopupMenuItem<ThemeMode>(
                value: ThemeMode.system,
                child: Text('跟随系统'),
              ),
              const PopupMenuItem<ThemeMode>(
                value: ThemeMode.light,
                child: Text('亮色模式'),
              ),
              const PopupMenuItem<ThemeMode>(
                value: ThemeMode.dark,
                child: Text('暗黑模式'),
              ),
            ],
          ),
        ],
      ),
      body: SafeArea(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      ElevatedButton(
                        onPressed: () {
                          ConfirmAlterDialog.show(
                            context: context,
                            title: '确认弹窗',
                            content: const Text(
                              '这是一个自定义内容的确认弹窗',
                              style: TextStyle(color: Colors.red),
                            ),
                            onConfirm: () {
                              print('确认弹窗');
                              Navigator.pop(context);
                            },
                          );
                        },
                        child: const Text('自定义内容确认弹窗'),
                      ),
                      ElevatedButton(
                        onPressed: () {
                          ConfirmAlterDialog.showWithText(
                            context: context,
                            title: '确认弹窗',
                            content: '这是一个确认弹窗',
                            onConfirm: () {
                              print('确认弹窗');
                              Navigator.pop(context);
                            },
                          );
                        },
                        child: const Text('确认弹窗'),
                      ),
                      Text(
                        '这是一个使用了主题颜色的文本',
                        style: Theme.of(context).textTheme.headlineSmall,
                      ),
                      const SizedBox(height: 20),
                      ElevatedButton(
                        onPressed: () {},
                        child: const Text('主题按钮'),
                      ),
                      Text(
                        '点击放大图片',
                        style: TextStyle(color: AppColors.of(context).primaryColor),
                      ),
                      GestureDetector(
                        onTap: _handleImageTap,
                        child: CachedNetworkImage(
                          imageUrl: 'https://picsum.photos/800/600',
                          width: 200,
                          height: 150,
                          fit: BoxFit.cover,
                        ),
                      ),
                      Text(
                        l10n.currentLanguage,
                        style: const TextStyle(fontSize: 20),
                      ),
                      const SizedBox(height: 10),
                      Text(
                        '${currentLocale.languageCode} - ${currentLocale.countryCode}',
                        style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 30),
                      ElevatedButton(
                        onPressed: _handleInfo,
                        child: Text(l10n.getInfo),
                      ),
                      const SizedBox(height: 20),
                      // 添加显示选择器的按钮
                      ElevatedButton(
                        onPressed: () => _showBottomPicker(context),
                        child: const Text('显示底部选择器'),
                      ),
                      const SizedBox(height: 20),
                      ElevatedButton(
                        onPressed: () => _showLinkedPicker(context),
                        child: const Text('显示双列联动选择器'),
                      ),
                      const SizedBox(height: 20),
                      ElevatedButton(
                        onPressed: () => _showTripleLinkedPicker(context),
                        child: const Text('显示三列联动选择器'),
                      ),
                      const SizedBox(height: 20),
                      InkWell(
                        onTap: () {
                          custom_picker.CustomDatePicker.show(
                            context: context,
                            initialDateTime: _editDateTime,
                            mode: custom_picker.DatePickerMode.editDateTime,
                            onChange: (DateTime dateTime) {
                              print(
                                '日期时间变更: ${custom_picker.CustomDatePicker.formatDate(dateTime)} ${custom_picker.CustomDatePicker.formatTime(dateTime)}',
                              );
                            },
                            onConfirm: (DateTime dateTime) {
                              setState(() {
                                _editDateTime = dateTime;
                              });
                              print(Tool.formatDate(dateTime.toString(), format: 'yyyy-MM-dd HH:mm:ss'));
                              print(
                                '确认日期时间: ${custom_picker.CustomDatePicker.formatDate(dateTime)} ${custom_picker.CustomDatePicker.formatTime(dateTime)}',
                              );
                            },
                            onCancel: () {
                              print('取消选择');
                            },
                          );
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey),
                            borderRadius: BorderRadius.circular(8.0),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(Tool.formatDate(_editDateTime.toString(), format: 'yyyy-MM-dd HH:mm')),
                              const Icon(Icons.calendar_today),
                            ],
                          ),
                        ),
                      ),
                      custom_picker.FilterDateWidget(
                        initialDateTime: DateTime.now(),
                        filterType: custom_picker.FilterType.year,
                        yearsBack: 100,
                        onDateTimeChanged: (value) {
                          setState(() {
                            print(value);
                          });
                        },
                      ),
                      // 多语言示例
                      Card(
                        margin: const EdgeInsets.all(16),
                        child: Padding(
                          padding: const EdgeInsets.all(16),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                l10n.multilingualDemo,
                                style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                              ),
                              const SizedBox(height: 10),
                              Text(l10n.demoText),
                              const SizedBox(height: 10),
                              Text('${l10n.currentTime}: ${DateTime.now().toString().substring(0, 19)}'),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
